document.addEventListener('DOMContentLoaded', function() {
    // 获取用户登录状态
    const isAuthenticated = document.body.getAttribute('data-user-authenticated') === 'true';
    
    const codeBlocks = document.querySelectorAll('pre');
    codeBlocks.forEach(function(codeBlock) {
        const container = document.createElement('div');
        container.className = 'code-block-container';
        
        const copyButton = document.createElement('button');
        copyButton.className = 'copy-btn';
        copyButton.textContent = '复制';
        
        codeBlock.parentNode.insertBefore(container, codeBlock);
        container.appendChild(codeBlock);
        container.appendChild(copyButton);
        
        copyButton.addEventListener('click', async function() {
            
            if (!isAuthenticated) {
                // 使用 layer 弹窗提示
                layer.confirm('请先登录后再复制代码', {
                    btn: ['去登录','取消'],
                    title: '提示'
                }, function(){
                    // 跳转到登录页面，并记录当前页面 URL
                    window.location.href = '/accounts/login/?next=' + encodeURIComponent(window.location.pathname);
                });
                return;
            }
            
            try {
                const code = codeBlock.textContent;
                await navigator.clipboard.writeText(code);
                
                copyButton.textContent = '已复制！';
                copyButton.classList.add('success');
                
                setTimeout(() => {
                    copyButton.textContent = '复制';
                    copyButton.classList.remove('success');
                }, 2000);
            } catch (err) {
                console.error('复制失败:', err);
                copyButton.textContent = '复制失败';
                copyButton.style.backgroundColor = '#dc3545';
                
                setTimeout(() => {
                    copyButton.textContent = '复制';
                    copyButton.style.backgroundColor = '';
                }, 2000);
            }
        });
    });
});